#!/bin/bash
set -e

# 全局配置
INSTALL_DIR="/opt/hp-lite"
BIN_PATH="/usr/local/bin/hp-lite"
CONFIG_FILE="$INSTALL_DIR/app.yml"
ROLE_FILE="$INSTALL_DIR/.hp_role"
LOG_DIR="/var/log/hp-lite"
IS_OPENWRT=0
RELEASE_URL="https://gitee.com/HServer/hp-lite/releases/download/6.0"

# 颜色定义
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
CYAN='\033[36m'
RESET='\033[0m'

# 退出时显示信息
show_exit_message() {
    echo -e "\n${CYAN}=================================${RESET}"
    echo -e "脚本开源地址：https://gitee.com/mch3318/hp-lite-Script"
    echo -e "HP项目开源地址：https://gitee.com/HServer/hp-lite"
    echo -e "Powered by ${RED}哔哩哔哩 墨城寒${RESET}"
    echo -e "${CYAN}=================================${RESET}\n"
    exit 0
}

# 捕获Ctrl+C和正常退出
trap show_exit_message INT EXIT

# 检测系统类型
is_openwrt() { [ -f /etc/openwrt_release ] && IS_OPENWRT=1 || IS_OPENWRT=0; }
is_openwrt

# 获取系统架构
get_arch() {
    case "$(uname -m)" in
        x86_64) echo "amd64";;
        aarch64|armv7l|armv6l) echo "arm";;
        mipsel) echo "mipsle";;
        mips) echo "mips";;
        *) echo "amd64";;
    esac
}

# 检测当前角色
detect_role() {
    [ -f "$ROLE_FILE" ] && cat "$ROLE_FILE" || echo "unknown"
}

# 下载HP-Lite
download_hp() {
    local role=$1
    local arch=$(get_arch)
    
    if [ "$role" = "server" ]; then
        echo -e "${YELLOW}正在下载 HP-Lite 服务端...${RESET}"
    else
        echo -e "${YELLOW}正在下载 HP-Lite 客户端...${RESET}"
    fi
    
    mkdir -p "$INSTALL_DIR" || {
        echo -e "${RED}无法创建目录 $INSTALL_DIR${RESET}"
        exit 1
    }
    cd "$INSTALL_DIR"
    
    if [ "$role" = "server" ]; then
        if [ "$arch" != "amd64" ]; then
            echo -e "${RED}错误：目前该脚本安装服务端仅支持amd64架构！${RESET}"
            exit 1
        fi
        pkg_name="hp-lite-server-amd64"
    else
        pkg_name="hp-lite-$arch"
    fi

    echo -e "下载地址: ${BLUE}$RELEASE_URL/$pkg_name${RESET}"
    if ! wget --no-check-certificate -O "$pkg_name" "$RELEASE_URL/$pkg_name"; then
        echo -e "${RED}下载失败！请检查：${RESET}"
        echo "1. 网络连接"
        echo "2. 该架构版本是否存在"
        echo "3. 服务端必须使用amd64架构"
        exit 1
    fi

    chmod +x "$pkg_name"
    ln -sf "$INSTALL_DIR/$pkg_name" "$BIN_PATH"
    
    echo -e "${GREEN}下载完成！${RESET}"
    echo "可执行文件: $BIN_PATH"
    sleep 1
}

# 服务端初始化配置
init_server() {
    echo -e "\n${GREEN}=== 服务端配置 ===${RESET}"
    
    mkdir -p "$INSTALL_DIR" || {
        echo -e "${RED}无法创建目录 $INSTALL_DIR${RESET}"
        exit 1
    }

    # 备份现有配置
    if [ -f "$CONFIG_FILE" ]; then
        backup_file="$CONFIG_FILE.$(date +%Y%m%d%H%M%S).bak"
        echo -e "${YELLOW}发现现有配置，已备份到: $backup_file${RESET}"
        cp "$CONFIG_FILE" "$backup_file"
    fi

    # 交互式配置
    echo -e "${BLUE}请填写配置参数（回车使用默认值）${RESET}"
    
    read -p "管理用户名 [admin]: " admin_user
    admin_user=${admin_user:-admin}
    
    read -p "管理密码 [123456]: " admin_pwd
    admin_pwd=${admin_pwd:-123456}
    
    read -p "管理端口 [9090]: " admin_port
    admin_port=${admin_port:-9090}
    
    read -p "指令端口 [16666]: " cmd_port
    cmd_port=${cmd_port:-16666}
    
    local server_ip=$(hostname -I | awk '{print $1}')
    read -p "服务器IP [$server_ip]: " tunnel_ip
    tunnel_ip=${tunnel_ip:-$server_ip}
    
    read -p "隧道端口 [9091]: " tunnel_port
    tunnel_port=${tunnel_port:-9091}

    # HTTP/HTTPS 转发设置
    while true; do
        echo -e "\n${YELLOW}是否开启HTTP/HTTPS域名转发？${RESET}"
        echo "1) 开启 (开放80/443端口)"
        echo "2) 关闭"
        read -p "请选择[1/2，默认2]: " domain_choice
        case $domain_choice in
            1) open_domain="true"; break ;;
            2|"") open_domain="false"; break ;;
            *) echo -e "${RED}无效输入，请重新选择${RESET}"; continue ;;
        esac
    done
    
    read -p "ACME邮箱 [admin@example.com]: " acme_email
    acme_email=${acme_email:-admin@example.com}
    
    read -p "ACME HTTP端口 [5634]: " acme_http_port
    acme_http_port=${acme_http_port:-5634}

    # 生成配置文件
    cat > "$CONFIG_FILE" <<EOF
admin:
  username: '$admin_user'
  password: '$admin_pwd'
  port: $admin_port

cmd:
  port: $cmd_port

tunnel:
  ip: '$tunnel_ip'
  port: $tunnel_port
  open-domain: $open_domain

acme:
  email: '$acme_email'
  http-port: '$acme_http_port'
EOF

    # 设置权限
    chmod 600 "$CONFIG_FILE"
    chown root:root "$CONFIG_FILE"
    
    echo -e "\n${GREEN}配置文件已生成：${RESET}"
    echo -e "路径: ${BLUE}$CONFIG_FILE${RESET}"
    echo "------------------------------------"
    cat "$CONFIG_FILE"
    echo "------------------------------------"

    # 创建服务
    if [ "$IS_OPENWRT" = "1" ]; then
        cat > /etc/init.d/hp-lite <<EOF
#!/bin/sh /etc/rc.common
START=99
USE_PROCD=1
PROG=$BIN_PATH
CONFIG=$CONFIG_FILE
start_service() {
    procd_open_instance
    procd_set_param command \$PROG -config \$CONFIG
    procd_set_param respawn
    procd_close_instance
}
stop_service() {
    killall hp-lite
}
EOF
        chmod +x /etc/init.d/hp-lite
        /etc/init.d/hp-lite enable
        if ! /etc/init.d/hp-lite restart; then
            echo -e "${RED}服务启动失败！${RESET}"
            logread | grep hp-lite | tail -20
            exit 1
        fi
    else
        cat > /etc/systemd/system/hp-lite.service <<EOF
[Unit]
Description=HP-Lite Server
After=network.target

[Service]
Type=simple
ExecStart=$BIN_PATH -config $CONFIG_FILE
Restart=always
RestartSec=3
User=root
WorkingDirectory=$INSTALL_DIR

[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload
        systemctl enable hp-lite
        if ! systemctl restart hp-lite; then
            echo -e "${RED}服务启动失败！${RESET}"
            journalctl -u hp-lite -n 20 --no-pager
            exit 1
        fi
    fi

    echo "server" > "$ROLE_FILE"
    
    # 显示结果
    clear
    echo -e "${GREEN}服务端启动成功！${RESET}"
    echo "============================"
    echo -e "管理面板: ${BLUE}http://${tunnel_ip}:${admin_port}${RESET}"
    echo -e "用户名: ${YELLOW}${admin_user}${RESET} 密码: ${YELLOW}${admin_pwd}${RESET}"
    echo -e "\n需要开放的端口:"
    echo -e "- 管理端口: ${YELLOW}${admin_port}${RESET} (TCP)"
    echo -e "- 指令端口: ${YELLOW}${cmd_port}${RESET} (TCP)"
    echo -e "- 隧道端口: ${YELLOW}${tunnel_port}${RESET} (TCP+UDP)"
    [ "$open_domain" = "true" ] && echo -e "- 域名端口: ${YELLOW}80 & 443${RESET} (TCP)"
    echo "============================"
    read -p "按回车键继续..."
}

# 客户端初始化配置
init_client() {
    echo -e "\n${GREEN}=== 客户端配置 ===${RESET}"
    
    # 清除可能的残留配置
    [ -f "$CONFIG_FILE" ] && rm -f "$CONFIG_FILE"
    
    # 获取连接码
    echo -e "${YELLOW}请从服务端管理面板创建设备获取连接码${RESET}"
    while true; do
        read -p "请输入连接码: " connect_code
        connect_code=$(echo "$connect_code" | tr -d '[:space:]')
        if [ -n "$connect_code" ]; then
            break
        fi
        echo -e "${RED}连接码不能为空！${RESET}"
    done

    # 创建服务
    if [ "$IS_OPENWRT" = "1" ]; then
        cat > /etc/init.d/hp-lite <<EOF
#!/bin/sh /etc/rc.common
START=99
USE_PROCD=1
PROG=$BIN_PATH
start_service() {
    procd_open_instance
    procd_set_param command \$PROG -c=\${connect_code}
    procd_set_param respawn
    procd_close_instance
}
EOF
        chmod +x /etc/init.d/hp-lite
        /etc/init.d/hp-lite enable
        if ! /etc/init.d/hp-lite restart; then
            echo -e "${RED}启动失败！${RESET}"
            logread | grep hp-lite | tail -20
            exit 1
        fi
    else
        cat > /etc/systemd/system/hp-lite.service <<EOF
[Unit]
Description=HP-Lite Client
After=network.target

[Service]
Type=simple
ExecStart=$BIN_PATH -c=${connect_code}
Restart=always
RestartSec=3
User=root

[Install]
WantedBy=multi-user.target
EOF
        systemctl daemon-reload
        systemctl enable hp-lite
        if ! systemctl restart hp-lite; then
            echo -e "${RED}启动失败！${RESET}"
            journalctl -u hp-lite -n 20 --no-pager
            exit 1
        fi
    fi

    echo "client" > "$ROLE_FILE"
    
    echo -e "\n${GREEN}客户端启动成功！${RESET}"
    echo -e "连接码: ${BLUE}${connect_code}${RESET}"
    read -p "按回车键继续..."
}

# 服务管理
service_control() {
    local action=$1
    
    if [ "$IS_OPENWRT" = "1" ]; then
        case $action in
            start) /etc/init.d/hp-lite start ;;
            stop) /etc/init.d/hp-lite stop ;;
            restart) /etc/init.d/hp-lite restart ;;
            status) /etc/init.d/hp-lite status ;;
        esac
    else
        case $action in
            start) systemctl start hp-lite ;;
            stop) systemctl stop hp-lite ;;
            restart) systemctl restart hp-lite ;;
            status) systemctl status hp-lite --no-pager ;;
        esac
    fi
    
    [ "$action" != "status" ] && echo "HP-Lite 已${action}"
    sleep 1
}

# 查看日志
view_log() {
    echo -e "\n${BLUE}=== 日志信息 ===${RESET}"
    
    if [ "$IS_OPENWRT" = "1" ]; then
        echo -e "日志位置: ${YELLOW}/var/log/messages${RESET} (筛选hp-lite)"
        echo "------------------------------------"
        logread | grep hp-lite | tail -50 || echo "暂无日志"
    else
        echo -e "日志位置: ${YELLOW}/var/log/syslog${RESET} 或 ${YELLOW}journalctl -u hp-lite${RESET}"
        echo "------------------------------------"
        if [ -f "/var/log/syslog" ]; then
            grep hp-lite /var/log/syslog | tail -50 || echo "暂无系统日志"
        else
            journalctl -u hp-lite -n 50 --no-pager || echo "暂无日志"
        fi
    fi
    echo "------------------------------------"
    read -p "按回车键继续..."
}

# 卸载HP-Lite
uninstall_hp() {
    echo -e "\n${RED}=== 卸载 HP-Lite ===${RESET}"
    
    # 停止服务
    if [ "$IS_OPENWRT" = "1" ]; then
        /etc/init.d/hp-lite stop >/dev/null 2>&1
        /etc/init.d/hp-lite disable >/dev/null 2>&1
        rm -f /etc/init.d/hp-lite
    else
        systemctl stop hp-lite >/dev/null 2>&1
        systemctl disable hp-lite >/dev/null 2>&1
        rm -f /etc/systemd/system/hp-lite.service
        systemctl daemon-reload
    fi
    
    # 删除文件和日志
    rm -rf "$INSTALL_DIR"
    rm -f "$BIN_PATH"
    rm -f "$ROLE_FILE"
    
    # 清理日志
    echo -e "${YELLOW}正在清理日志...${RESET}"
    if [ "$IS_OPENWRT" = "1" ]; then
        logread | grep -v hp-lite > /tmp/syslog.tmp && mv /tmp/syslog.tmp /var/log/messages
    else
        journalctl --vacuum-time=1d >/dev/null 2>&1
        rm -f /var/log/hp-lite.log 2>/dev/null
    fi
    
    echo -e "${GREEN}卸载完成！所有相关文件和日志已清理。${RESET}"
    sleep 2
}

# 服务端菜单
server_menu() {
    while true; do
        clear
        echo -e "${BLUE}==== HP-Lite 6.0 服务端 ====${RESET}"
        echo "1) 下载/更新"
        echo "2) 初始化配置"
        echo "3) 启动服务"
        echo "4) 停止服务"
        echo "5) 重启服务"
        echo "6) 查看状态"
        echo "7) 查看日志"
        echo "8) 卸载"
        echo "0) 返回"
        echo "---------------------"
        read -p "请选择 [0-8]: " choice
        
        case $choice in
            1) download_hp "server" ;;
            2) init_server ;;
            3) service_control start ;;
            4) service_control stop ;;
            5) service_control restart ;;
            6) service_control status ;;
            7) view_log ;;
            8) uninstall_hp; break ;;
            0) break ;;
            *) echo -e "${RED}无效选择！${RESET}"; sleep 1 ;;
        esac
    done
}

# 客户端菜单
client_menu() {
    while true; do
        clear
        echo -e "${GREEN}==== HP-Lite 6.0 客户端 ====${RESET}"
        echo "1) 下载/更新"
        echo "2) 初始化配置"
        echo "3) 启动服务"
        echo "4) 停止服务"
        echo "5) 重启服务"
        echo "6) 查看状态"
        echo "7) 查看日志"
        echo "8) 卸载"
        echo "0) 返回"
        echo "---------------------"
        read -p "请选择 [0-8]: " choice
        
        case $choice in
            1) download_hp "client" ;;
            2) init_client ;;
            3) service_control start ;;
            4) service_control stop ;;
            5) service_control restart ;;
            6) service_control status ;;
            7) view_log ;;
            8) uninstall_hp; break ;;
            0) break ;;
            *) echo -e "${RED}无效选择！${RESET}"; sleep 1 ;;
        esac
    done
}

# 主菜单
main_menu() {
    while true; do
        clear
        echo -e "${YELLOW}==== HP-Lite 6.0 管理脚本 ====${RESET}"
        echo "1) 服务端管理"
        echo "2) 客户端管理"
        echo "0) 退出"
        echo "---------------------"
        read -p "请选择 [0-2]: " choice
        
        case $choice in
            1) server_menu ;;
            2) client_menu ;;
            0) show_exit_message ;;
            *) echo -e "${RED}无效选择！${RESET}"; sleep 1 ;;
        esac
    done
}

# 启动入口
role=$(detect_role)
case $role in
    server) server_menu ;;
    client) client_menu ;;
    *) main_menu ;;
esac